"This is the locale selecting middleware that will look at accept headers"
import datetime
from django.conf import settings
from django.http import HttpResponseRedirect, JsonResponse
from django.utils.deprecation import MiddlewareMixin

# from database.models import Token

from rest_framework import status

from databases.models import *
from databases.serializers import *


class TokenMiddleware(MiddlewareMixin):
    """ APP用户的TOKEN登陆验证 """
    response_redirect_class = HttpResponseRedirect

    ''' 静态资源过滤 '''
    __RESOURCE = ["versionInfo"]

    def process_request(self, request):
        pass
        # app_token = request.META.get('HTTP_APP_TOKEN', None)  # django header中的参数回带上HTTP
        #
        # allowed_not_login_url = settings.ALLOWED_NOT_LOGIN_URL
        # do_vaildata = True  # 是否需要经过验证
        # if allowed_not_login_url is not None:
        #     _path = request.path
        #     # 跳过不需要验证的部分
        #     if '*' in allowed_not_login_url or \
        #                     _path in allowed_not_login_url:
        #         do_vaildata = False  # 不需要验证
        #
        # if do_vaildata:
        #     try:
        #         # token 验证通过
        #         token = Token.objects.get(is_active=True, app_token=app_token, overdue__lte=datetime.now())
        #         request.session['app_token'] = token
        #     except:
        #         data = {
        #             "message": '用户未登录或身份已过期!'
        #         }
        #         return JsonResponse(data)

    def process_view(self, request, callback, callback_args, callback_kwargs):
        # #部分请求不过滤
        # request_path = "/".join(request.path.split('/')[:-1])
        # is_resource = False
        # for resource_path in self.__RESOURCE:
        #     if resource_path in request_path:
        #         is_resource = True
        #         break

        _now = datetime.datetime.now()
        overdue_time = _now + datetime.timedelta(days=20)
        data = {}
        app_token = request.META.get('HTTP_APPTOKEN', None)  # django header中的参数回带上HTTP
        # if hasattr(settings, 'PERMISSION_VALIDATE') and  not is_resource:
        if hasattr(settings, 'PERMISSION_VALIDATE'):
            permission_validate = settings.PERMISSION_VALIDATE
            if permission_validate:  # 如果需要验证
                try:
                    do_vaildata = True
                    if hasattr(callback.cls, 'permission_validate'):
                        do_vaildata = getattr(callback.cls, 'permission_validate')

                    if do_vaildata:
                        try:
                            # token 验证通过
                            token = Token.objects.get(modify_time__lte=overdue_time,
                                                      token=app_token
                                                      )
                            # request.session['app_token'] = TokenSerializer(token).data
                            setattr(request, 'app_user', token.user)
                            # return JsonResponse(AppUserSerializer(token.user).data)
                            # setattr(request, 'app_user', AppUser.objects.get(id=1))
                        except Exception as e:
                            #web session验证
                            #
                            userInfo = request.session.get('web_user',None)
                            if userInfo:
                                setattr(request, 'app_user', userInfo)
                            else:
                                data['detail'] = {
                                    "message": '用户未登录或身份已过期!',
                                    "code": 444
                                }
                                return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST)
                except:
                    pass
